﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.Linq;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using ESRI.ArcGIS.ADF.BaseClasses;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.ADF;
using PlanningGIS.Framework.Controls;
using PlanningGIS.Framework;
using PlanningGIS.Symbol;
using PlanningGIS.Win.Controls;
using PlanningGIS.Framework.Config;
using PlanningGIS.ArcGIS;
using PlanningGIS.Framework.Rule;
using PlanningGIS.Util.Log;

namespace PlanningGIS.TocContextMenu
{
    /// <summary>
    /// 作用：Symbolize操作类
    /// </summary>
    public class SymbolizeUtility
    {
        /// <summary>
        /// 
        /// </summary>
        public static List<SymbolItem> markSymbols;
        /// <summary>
        /// 
        /// </summary>
        public static List<SymbolItem> lineSymbols;
        /// <summary>
        /// 
        /// </summary>
        public static List<SymbolItem> fillSymbols;

        /// <summary>
        /// 根据规则符号化
        /// </summary>
        /// <param name="pFeatLyrs">符号化图层</param>
        /// <param name="pStatusBar">当前状态栏</param>
        /// <param name="stylePath">符号库完整路径</param>
        /// <param name="angleField">旋转角度字段</param>
        /// <param name="symbolRotationType">旋转方式</param>
        /// <param name="ruleName">符号化规则</param>
        /// <param name="symbolField">符号化字段</param>
        public static void SymbolizeLyrsByRule(List<IFeatureLayer> pFeatLyrs, IStatusBar pStatusBar, string stylePath, string angleField,
            esriSymbolRotationType symbolRotationType, string ruleName, string symbolField, bool uniqeOnly)
        {
            if (pFeatLyrs == null || pFeatLyrs.Count == 0) return;


            if (pStatusBar != null) pStatusBar.ShowProgressBar("批量符号化", 0, pFeatLyrs.Count, 1);
            bool hasErr = false;

            foreach (IFeatureLayer pFeatLyr in pFeatLyrs)
            {
                try
                {
                    Application.DoEvents();
                    if (pStatusBar != null)
                    {
                        pStatusBar.StepProgressBar();
                        pStatusBar.SetMessage("正在符号化[" + pFeatLyr.Name + "]图层...");
                    }
                    if (!(pFeatLyr is IGeoFeatureLayer))
                        continue;
                    if (pFeatLyr.FeatureClass.FeatureType == esriFeatureType.esriFTAnnotation)
                        continue;
                    SymbolizeFeatLyr(pFeatLyr as IGeoFeatureLayer, stylePath, angleField, symbolRotationType, ruleName, symbolField,uniqeOnly);
                }
                catch (Exception ex)
                {
                    hasErr = true;
                    if (MsgHelper.ShowYesOrNoQueryMsgBox("符号化[" + pFeatLyr.Name + "]图层时发生错误，原因：" + ex.Message +
                            "是否继续其它图层的符号化？") == DialogResult.Yes)
                        continue;
                    else
                        break;
                }
            }
            if (pStatusBar != null)
            {
                pStatusBar.HideProgressBar();
                pStatusBar.SetMessage("");
            }
            if (hasErr)
            {
                MsgHelper.ShowInfomationMsgbox("符号化完毕，但是有部分未能成功！");
            }
            else
            {
                MsgHelper.ShowInfomationMsgbox("符号化完毕！");
            }
           
        }

        /// <summary>
        /// 生产默认符号
        /// </summary>
        /// <param name="pGeoFeatLyr"></param>
        /// <returns></returns>
        private static ISymbol GetDefaultSymbol(IGeoFeatureLayer pGeoFeatLyr, out PlanningGIS.ArcGIS.zjgisStyleGalleryType styleType)
        {
            ISymbol pDefaultSymbol = null;

            switch (pGeoFeatLyr.FeatureClass.ShapeType)
            {
                case esriGeometryType.esriGeometryPoint:
                    styleType = PlanningGIS.ArcGIS.zjgisStyleGalleryType.MarkerSymbols;
                    IMarkerSymbol pMarkerSym = new SimpleMarkerSymbolClass();
                    pMarkerSym.Size = 2;
                    pDefaultSymbol = pMarkerSym as ISymbol;
                    break;
                case esriGeometryType.esriGeometryPolyline:
                    styleType = PlanningGIS.ArcGIS.zjgisStyleGalleryType.LineSymbols;
                    ILineSymbol pLineSym = new SimpleLineSymbolClass();
                    pDefaultSymbol = pLineSym as ISymbol;
                    break;
                case esriGeometryType.esriGeometryPolygon:
                    styleType = PlanningGIS.ArcGIS.zjgisStyleGalleryType.FillSymbols;
                    IRgbColor pRgbColor = new RgbColorClass();
                    pRgbColor.Red = 0;
                    pRgbColor.Green = 255;
                    pRgbColor.Blue = 255;
                    IFillSymbol pFillSym = new SimpleFillSymbolClass();
                    pFillSym.Color = pRgbColor;
                    pDefaultSymbol = pFillSym as ISymbol;
                    break;

                default :
                    styleType = PlanningGIS.ArcGIS.zjgisStyleGalleryType.MarkerSymbols;
                    break;
            }
            return pDefaultSymbol;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="styleType"></param>
        /// <returns></returns>
        private static List<SymbolItem> GetSymbols(PlanningGIS.ArcGIS.zjgisStyleGalleryType styleType)
        {
            switch (styleType)
            {
                case PlanningGIS.ArcGIS.zjgisStyleGalleryType.MarkerSymbols:
                    return markSymbols;
                case PlanningGIS.ArcGIS.zjgisStyleGalleryType.LineSymbols:
                    return lineSymbols;
                case PlanningGIS.ArcGIS.zjgisStyleGalleryType.FillSymbols:
                    return fillSymbols;
                default :
                    return null;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="symbols"></param>
        /// <param name="styleType"></param>
        private static void SetSymbols(List<SymbolItem> symbols, PlanningGIS.ArcGIS.zjgisStyleGalleryType styleType)
        {
            switch (styleType)
            {
                case PlanningGIS.ArcGIS.zjgisStyleGalleryType.MarkerSymbols:
                    markSymbols = symbols;
                    break;

                case PlanningGIS.ArcGIS.zjgisStyleGalleryType.LineSymbols:
                    lineSymbols = symbols;
                    break;

                case PlanningGIS.ArcGIS.zjgisStyleGalleryType.FillSymbols:
                    fillSymbols = symbols;
                    break;

                default:
                    return;
            }
        }

        /// <summary>
        /// 根据规则符号化图层
        /// </summary>
        /// <param name="pGeoFeatLyr">符号化图层</param>
        /// <param name="stylePath">符号库完整路径</param>
        /// <param name="angleField">旋转角度字段</param>
        /// <param name="symbolRotationType">旋转方式</param>
        /// <param name="ruleName">符号化规则</param>
        /// <param name="symbolField">符号化字段</param>
        /// <param name="uniqueOnly">是否仅列出唯一值</param>
        public static void SymbolizeFeatLyr(IGeoFeatureLayer pGeoFeatLyr, string stylePath, string angleField,
            esriSymbolRotationType symbolRotationType, string ruleName, string symbolField,bool uniqueOnly)
        {
            if (pGeoFeatLyr.FeatureClass.Fields.FindField(symbolField) < 0) return;

            IUniqueValueRenderer pUniqueRender = new UniqueValueRendererClass();
            pUniqueRender.FieldCount = 1;
            pUniqueRender.set_Field(0, symbolField);

            #region DefaultSymbol
            PlanningGIS.ArcGIS.zjgisStyleGalleryType styleType = PlanningGIS.ArcGIS.zjgisStyleGalleryType.LineSymbols;
            ISymbol pDefaultSymbol = GetDefaultSymbol(pGeoFeatLyr, out styleType);

            pUniqueRender.DefaultLabel = "其它代码";
            pUniqueRender.DefaultSymbol = pDefaultSymbol;
            pUniqueRender.UseDefaultSymbol = true;
            #endregion

            List<string> fcodes;

            #region 通过要素类的别名找到对应的规则
            string aliasName = pGeoFeatLyr.FeatureClass.AliasName;
            fcodes = GetFcodesFromAliasName(aliasName,ruleName);
            #endregion

            #region 如果通过规则找不到FCODE的集合,或者用户要求用唯一值列的话，则需要遍历数据来获取了
            if (fcodes.Count == 0 || uniqueOnly)
            {
                fcodes = new List<string>();
                ArrayList fcl = FieldHelper.GetUniqueValuesByQueryDef(pGeoFeatLyr.FeatureClass, symbolField);
                for (int i = 0; i < fcl.Count; i++)
                {
                    fcodes.Add(fcl[i].ToString ());
                }


                ////遍历所有该图层唯一值
                //IFeatureCursor pFeatCursor = pGeoFeatLyr.FeatureClass.Search(null, false);
                //IDataStatistics pDataStatistics = new DataStatisticsClass();
                //pDataStatistics.Field = symbolField;
                //pDataStatistics.Cursor = pFeatCursor as ICursor;
                //IEnumerator pEnum = pDataStatistics.UniqueValues;
                //while (pEnum.MoveNext())
                //{
                //    fcodes.Add(pEnum.Current.ToString());
                //}
            }
            #endregion

            string sTitile = "";
            List<SymbolItem> m_List = GetSymbols(styleType);// SymbolCom.GetStyle(styleType, stylePath, null);
            if (m_List == null)
            {
                m_List = SymbolHelper.GetStyles(styleType, stylePath);
                SetSymbols(m_List, styleType);
            }

            foreach (string fcode in fcodes)
            {
                sTitile = GetSymbolTitleByRule(fcode,ruleName);

                ISymbol pSymbol = null;
                foreach (SymbolItem m_SymbolItem in m_List)
                {
                    if (m_SymbolItem.Name == fcode)
                    {
                        pSymbol = m_SymbolItem.Symbol as ISymbol;
                        break;
                    }
                }

                if (pSymbol == null)
                {
                    pSymbol = pDefaultSymbol;
                }
                pUniqueRender.AddValue(fcode, "", pSymbol);
                pUniqueRender.set_Label(fcode, sTitile);
            }

            pUniqueRender.ColorScheme = "Custom";
            pUniqueRender.set_FieldType(0, true);

            //把符号化赋给图层
            pGeoFeatLyr.Renderer = pUniqueRender as IFeatureRenderer;
            pGeoFeatLyr.DisplayField = symbolField;

            // 如果是点层,需要对角度进行旋转
            if (pGeoFeatLyr.FeatureClass.ShapeType == esriGeometryType.esriGeometryPoint)
            {
                if (angleField == "") return;
                if (pGeoFeatLyr.FeatureClass.Fields.FindField(angleField) < 0) return;
                IRotationRenderer pRotationRenderer = pGeoFeatLyr.Renderer as IRotationRenderer;
                pRotationRenderer.RotationField = angleField;

                //旋转方式
                pRotationRenderer.RotationType = symbolRotationType;
                pGeoFeatLyr.Renderer = pRotationRenderer as IFeatureRenderer;
            }

        }

        /// <summary>
        /// 通过要素类别名获取分类代码集合
        /// </summary>
        /// <param name="aliasName">要素类别名</param>
        /// <param name="ruleName">规则名称</param>
        /// <returns></returns>
        public static List<string> GetFcodesFromAliasName(string aliasName,string ruleName)
        {
            List<string> fcodes = new List<string>();
            DataImportRule dataImportRuleCur = null;
            foreach (DataImportRule dataImportRule in RuleConfig.DataBuilding.BuildingRules)
            {
                if (dataImportRule.RuleName == ruleName)
                {
                    dataImportRuleCur = dataImportRule;
                    break;
                }
            }
            if (dataImportRuleCur == null) return fcodes;

            foreach (DlgTargetFeatureClass featureClass in dataImportRuleCur.dlgTargetFeatureClasses)
            {
                if (featureClass.FeatureClassAliasName == aliasName)
                {
                    foreach (FeatureCode code in featureClass.featureCodes)
                    {
                        fcodes.Add(code.FCODE.Trim());
                    }
                }
            }

            return fcodes;
        }

        /// <summary>
        /// 通过规则得到符号名称
        /// </summary>
        /// <param name="fcode">分类代码</param>
        /// <param name="ruleName">规则名称</param>
        /// <returns></returns>
        public static string GetSymbolTitleByRule(string fcode,string ruleName)
        {
            DataImportRule dataImportRuleCur = null;
            foreach (DataImportRule dataImportRule in RuleConfig.DataBuilding.BuildingRules)
            {
                if (dataImportRule.RuleName == ruleName)
                {
                    dataImportRuleCur = dataImportRule;
                    break;
                }
            }
            if (dataImportRuleCur == null) return fcode;
            foreach (DlgTargetFeatureClass featureClass in dataImportRuleCur.dlgTargetFeatureClasses)
            {
                foreach (FeatureCode code in featureClass.featureCodes)
                {
                    if (code.FCODE == null || code.FNAME == null) continue;
                    if (code.FCODE.Trim() == fcode.Trim())
                    {
                        return code.FCODE.Trim() + "  " + code.FNAME.Trim();
                    }
                }
            }
            return fcode;
        }


        /// <summary>
        /// 根据字段唯一值进行符号化
        /// </summary>
        /// <param name="pFeatLyrs">符号化图层</param>
        /// <param name="pStatusBar">状态栏</param>
        /// <param name="stylePath">符号库完整路径</param>
        /// <param name="angleField">旋转角度字段</param>
        /// <param name="symbolRotationType">旋转方式</param>
        /// <param name="symbolField1">字段1</param>
        /// <param name="symbolField2">字段2</param>
        /// <param name="symbolField3">字段3</param>
        /// <param name="conStr">连接字符</param>
        public static void SymbolizeLyrsByUniqueFields(List<IFeatureLayer> pFeatLyrs, IStatusBar pStatusBar, string stylePath, string angleField,
            esriSymbolRotationType symbolRotationType,string symbolField1,string symbolField2,string symbolField3,string conStr)
        {
            if (pFeatLyrs == null || pFeatLyrs.Count == 0) return;

            if (symbolField1 == "")
            {
                MsgHelper.ShowInfomationMsgbox("请设置需要取唯一值的字段！");
                return;
            }

            if (pStatusBar != null) pStatusBar.ShowProgressBar("批量符号化", 0, pFeatLyrs.Count, 1);

            bool hasErr = false;

            foreach (IFeatureLayer pFeatLyr in pFeatLyrs)
            {
                try
                {
                    Application.DoEvents();

                    if (pStatusBar != null)
                    {
                        pStatusBar.StepProgressBar();
                        pStatusBar.SetMessage("正在符号化[" + pFeatLyr.Name + "]图层...");
                    }
                    if (!(pFeatLyr is IGeoFeatureLayer))
                        continue;
                    if (pFeatLyr.FeatureClass.FeatureType == esriFeatureType.esriFTAnnotation)
                        continue;
                    SymbolizeFeatLyr(pFeatLyr as IGeoFeatureLayer, stylePath, angleField, symbolRotationType, symbolField1, symbolField2, symbolField3, conStr);
                }
                catch (Exception ex)
                {
                    hasErr = true;
                    if (MsgHelper.ShowYesOrNoQueryMsgBox("符号化[" + pFeatLyr.Name + "]图层时发生错误，原因：" + ex.Message +
                            "是否继续其它图层的符号化？") == DialogResult.Yes)
                        continue;
                    else
                        break;
                }
            }

            if (pStatusBar != null)
            {
                pStatusBar.HideProgressBar();
                pStatusBar.SetMessage("");
            }
            if (hasErr)
            {
                MsgHelper.ShowInfomationMsgbox("符号化完毕，但是有部分未能成功！");
            }
            else
            {
                MsgHelper.ShowInfomationMsgbox("符号化完毕！");
            }
            
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="pGeoFeatLyr"></param>
        /// <param name="stylePath"></param>
        /// <param name="angleField"></param>
        /// <param name="symbolRotationType"></param>
        /// <param name="symbolField1"></param>
        /// <param name="symbolField2"></param>
        /// <param name="symbolField3"></param>
        /// <param name="conStr"></param>
        public static void SymbolizeFeatLyr(IGeoFeatureLayer pGeoFeatLyr, string stylePath, string angleField,
            esriSymbolRotationType symbolRotationType, string symbolField1, string symbolField2, string symbolField3, string conStr)
        {
            IUniqueValueRenderer pUniqueRender = new UniqueValueRendererClass();
            string displayField;
            if (!string.IsNullOrEmpty(conStr)) pUniqueRender.FieldDelimiter = conStr;

            if (symbolField2 != "")
            {
                if (symbolField3 != "")
                {
                    pUniqueRender.FieldCount = 3;
                    pUniqueRender.set_Field(2, symbolField3);

                    displayField = symbolField1 + conStr + symbolField2 + conStr + symbolField3;
                }
                else
                {
                    pUniqueRender.FieldCount = 2;
                    displayField = symbolField1 + conStr + symbolField2;
                }
                pUniqueRender.set_Field(1, symbolField2);

            }
            else
            {
                pUniqueRender.FieldCount = 1;
                displayField = symbolField1;
            }
            pUniqueRender.set_Field(0, symbolField1);

            #region DefaultSymbol
            PlanningGIS.ArcGIS.zjgisStyleGalleryType styleType = PlanningGIS.ArcGIS.zjgisStyleGalleryType.LineSymbols;
            ISymbol pDefaultSymbol = GetDefaultSymbol(pGeoFeatLyr, out styleType);

            pUniqueRender.DefaultSymbol = pDefaultSymbol;
            pUniqueRender.UseDefaultSymbol = true;
            #endregion

            #region 获取所有的唯一值

            ArrayList list1 = new ArrayList();
            ArrayList list2 = new ArrayList();
            ArrayList list3 = new ArrayList();

            List<string> uniques = new List<string>();
            
            if (symbolField1 != "")
            {
                if (pGeoFeatLyr.FeatureClass.Fields.FindField(symbolField1) < 0) return;

                list1 = FieldHelper.GetUniqueValuesByQueryDef(pGeoFeatLyr.FeatureClass, symbolField1);
                if (list1.Count == 0) return;

                //IFeatureWorkspace pFeatWs = (pGeoFeatLyr.FeatureClass as IDataset).Workspace as IFeatureWorkspace;
                //IQueryDef pQueryDef = pFeatWs.CreateQueryDef();
                //pQueryDef.Tables = (pGeoFeatLyr.FeatureClass as IDataset).Name;
                //pQueryDef.SubFields = "DISTINCT " + symbolField1;
                //ICursor pCursor = pQueryDef.Evaluate();

                //IRow pRow = pCursor.NextRow();
                //while (pRow != null)
                //{
                //    list1.Add(pRow.get_Value(0));

                //    pRow = pCursor.NextRow();
                //}
                //Marshal.ReleaseComObject(pCursor);

                //IFeatureCursor pFeatCur = pGeoFeatLyr.FeatureClass.Search(null, false);

                //IDataStatistics pDataStat = new DataStatisticsClass();
                //pDataStat.Field = symbolField1;
                //pDataStat.Cursor = pFeatCur as ICursor;
                //IEnumerator pEnumVar = pDataStat.UniqueValues;

                //Marshal.ReleaseComObject(pFeatCur);

                //if (pDataStat.UniqueValueCount == 0)
                //{
                //    return;
                //}


                ////问题出在这里，但是 WHY？
                //pEnumVar.Reset();
                //while (pEnumVar.MoveNext())
                //{
                //    //list1.Add(pEnumVar.Current.ToString());
                //}

                
            }
            if (symbolField2 !="")
            {
                if (pGeoFeatLyr.FeatureClass.Fields.FindField(symbolField2) < 0) return;

                list2 = FieldHelper.GetUniqueValuesByQueryDef(pGeoFeatLyr.FeatureClass, symbolField2);

                if(symbolField3 !="")
                {
                    list3 = FieldHelper.GetUniqueValuesByQueryDef(pGeoFeatLyr.FeatureClass, symbolField3);

                }
            }

            for (int i = 0; i < list1.Count; i++)
            {
                if (symbolField2 !="")
                {
                    for (int j = 0; j < list2.Count; j++)
                    {
                        if (symbolField3 !="")
                        {
                            for (int k = 0; k < list3.Count; k++)
                            {
                                uniques.Add(list1[i].ToString() + conStr + list2[j].ToString() + conStr + list3[k].ToString());
                            }
                        }
                        else
                        {
                            uniques.Add(list1[i].ToString() + conStr + list2[j].ToString());
                        }
                    }
                }
                else
                {
                    uniques.Add(list1[i].ToString());
                }
            }
            #endregion

            List<SymbolItem> m_List = GetSymbols(styleType);// SymbolCom.GetStyle(styleType, stylePath, null);
            if (m_List == null)
            {
                m_List = SymbolHelper.GetStyles(styleType, stylePath);
                //List<SymbolItem> m_List = SymbolCom.GetStyle(styleType, stylePath, null);
                SetSymbols(m_List, styleType);
            }
            foreach (string unique in uniques)
            {
                ISymbol pSymbol = null;
                var query = from r in m_List
                            where r.Name == unique
                            select r;
                string category = "";

                if (query.Count() == 0)
                {
                    pSymbol = pDefaultSymbol;
                }
                else
                {

                    SymbolItem symbolitem = null;
                    foreach (SymbolItem value in query)
                    {
                        symbolitem = value;
                        break;
                    }
                    pSymbol = symbolitem.Symbol as ISymbol;
                    category = symbolitem.Category;
                }

                try
                {
                    pUniqueRender.AddValue(unique, displayField, pSymbol);
                    pUniqueRender.set_Label(unique, unique + (category == "" ? "" : " " + category));
                } 
                catch { }
            }

            pUniqueRender.ColorScheme = "Custom";
            pUniqueRender.set_FieldType(0, true);

            //把符号化赋给图层
            pGeoFeatLyr.Renderer = pUniqueRender as IFeatureRenderer;
            //pGeoFeatLyr.DisplayField = displayField;

            // 如果是点层,需要对角度进行旋转
            if (pGeoFeatLyr.FeatureClass.ShapeType == esriGeometryType.esriGeometryPoint)
            {
                if (angleField == "") return;
                if (pGeoFeatLyr.FeatureClass.Fields.FindField(angleField) < 0) return;
                IRotationRenderer pRotationRenderer = pGeoFeatLyr.Renderer as IRotationRenderer;
                pRotationRenderer.RotationField = angleField;

                //旋转方式
                pRotationRenderer.RotationType = symbolRotationType;
                pGeoFeatLyr.Renderer = pRotationRenderer as IFeatureRenderer;
            }


        }

        /// <summary>
        /// 符号化集合中的图层
        /// </summary>
        /// <param name="statusController"></param>
        /// <param name="pFeatLyrs"></param>
        public static void SymbolGeoFeatLyrs(List<IFeatureLayer> pFeatLyrs, IApplication m_Application)
        {
            if (AppConfig.SystemConfig == null || AppConfig.SystemConfig.符号化 == null)
            {
                LogHelper.WriteErrLog("配置中的符号化为空，请检查配置是否正确！");
                return;
            }
            try
            {
                //得到默认符号库
                if (string.IsNullOrWhiteSpace(AppConfig.SystemConfig.符号化.默认符号库) ||
                   !System.IO.Path.GetExtension(AppConfig.SystemConfig.符号化.默认符号库).Equals(".STYLE", StringComparison.CurrentCultureIgnoreCase))
                {
                    OpenFileDialog dlg = new OpenFileDialog();
                    dlg.Multiselect = false;
                    dlg.RestoreDirectory = true;
                    dlg.Title = "选择符号库";
                    dlg.Filter = "符号库|*.Style";
                    if (dlg.ShowDialog() == DialogResult.OK)
                    {
                        AppConfig.SystemConfig.符号化.默认符号库 = dlg.FileName;
                        ConfigHelper.SaveObject<PlanningGIS.Framework.Config.SystemConfig>(AppConfig.SystemConfig);
                    }
                }
                string stylePath = AppConfig.StylePath + "\\" + AppConfig.SystemConfig.符号化.默认符号库;
                if (!System.IO.File.Exists(stylePath))
                {
                    MsgHelper.ShowErrorMsgbox(stylePath + "\r\n相应路径下不存在着符号库文件，请修改默认符号库路径!");
                    return;
                }
                //默认符号化字段
                if (string.IsNullOrWhiteSpace(AppConfig.SystemConfig.符号化.符号化字段))
                {
                    FrmText frm = new FrmText();
                    frm.Title = "符号化依据字段";
                    frm.ToolTip = "输入";
                    frm.AllowNull = false;
                    if (frm.ShowDialog() != DialogResult.OK) return;
                    AppConfig.SystemConfig.符号化.符号化字段 = frm.Value;
                    ConfigHelper.SaveObject<PlanningGIS.Framework.Config.SystemConfig>(AppConfig.SystemConfig);
                }
                //找到默认分类代码规则
                foreach (IFeatureLayer pFeatLyr in pFeatLyrs)
                {
                    try
                    {
                        Application.DoEvents();
                        m_Application.StatusBar.SetMessage("正在符号化" + pFeatLyr.Name + "图层");
                        if (!(pFeatLyr is IGeoFeatureLayer))
                            continue;
                        SymbolGeoFeatLyr(pFeatLyr as IGeoFeatureLayer, stylePath);
                    }
                    catch (Exception ex)
                    {
                        if (MessageBox.Show("符号化" + pFeatLyr.Name + "图层时发生错误，原因：" + ex.Message +
                                "是否继续其它图层的符号化？", "出错询问", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                            continue;
                        else
                            break;
                    }
                }
                m_Application.StatusBar.SetMessage("");
                MessageBox.Show("符号化完毕！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show("符号化出错：" + ex.Message, "出错", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
          
        }

        /// <summary>
        /// 符号化图层
        /// </summary>
        /// <param name="pStyleGlry"></param>
        /// <param name="pGeoFeatLyr"></param>
        public static void SymbolGeoFeatLyr(IGeoFeatureLayer pGeoFeatLyr, string styleSet)
        {
            if (pGeoFeatLyr.FeatureClass.Fields.FindField(AppConfig.SystemConfig.符号化.符号化字段) < 0) return;
            IUniqueValueRenderer pUniqueRender = new UniqueValueRendererClass();
            pUniqueRender.FieldCount = 1;
            pUniqueRender.set_Field(0, AppConfig.SystemConfig.符号化.符号化字段);
            #region DefaultSymbol
            ISymbol pDefaultSymbol = null;
            PlanningGIS.ArcGIS.zjgisStyleGalleryType m_StyleType = PlanningGIS.ArcGIS.zjgisStyleGalleryType.LineSymbols;
            switch (pGeoFeatLyr.FeatureClass.ShapeType)
            {
                case esriGeometryType.esriGeometryPoint:
                    m_StyleType = PlanningGIS.ArcGIS.zjgisStyleGalleryType.MarkerSymbols;
                    IMarkerSymbol pMarkerSym = new SimpleMarkerSymbolClass();
                    pMarkerSym.Size = 2;
                    pDefaultSymbol = pMarkerSym as ISymbol;
                    break;
                case esriGeometryType.esriGeometryPolyline:
                    m_StyleType = PlanningGIS.ArcGIS.zjgisStyleGalleryType.LineSymbols;
                    ILineSymbol pLineSym = new SimpleLineSymbolClass();
                    pDefaultSymbol = pLineSym as ISymbol;
                    break;
                case esriGeometryType.esriGeometryPolygon:
                    m_StyleType = PlanningGIS.ArcGIS.zjgisStyleGalleryType.FillSymbols;
                    IRgbColor pRgbColor = new RgbColorClass();
                    pRgbColor.Red = 0;
                    pRgbColor.Green = 255;
                    pRgbColor.Blue = 255;
                    IFillSymbol pFillSym = new SimpleFillSymbolClass();
                    pFillSym.Color = pRgbColor;
                    pDefaultSymbol = pFillSym as ISymbol;
                    break;
            }
            #endregion

            pUniqueRender.DefaultSymbol = pDefaultSymbol;
            pUniqueRender.UseDefaultSymbol = true;

            List<string> fcodes;
            #region 通过要素类的别名找到对应的规则
            string aliasName = pGeoFeatLyr.FeatureClass.AliasName;
            fcodes = GetFcodesFromAliasName(aliasName);
            #endregion

            #region 如果通过规则找不到FCODE的集合，则需要遍历数据来获取了
            if (fcodes.Count == 0)
            {
                //遍历所有该图层唯一值
                IFeatureCursor pFeatCursor = pGeoFeatLyr.FeatureClass.Search(null, false);
                IDataStatistics pDataStatistics = new DataStatisticsClass();
                pDataStatistics.Field = AppConfig.SystemConfig.符号化.符号化字段;
                pDataStatistics.Cursor = pFeatCursor as ICursor;
                IEnumerator pEnum = pDataStatistics.UniqueValues;
                while (pEnum.MoveNext())
                {
                    fcodes.Add(pEnum.Current.ToString());
                }
            }
            #endregion

            //////遍历所有该图层唯一值
            ////如果getbyrule为true，即未设置别名字段，或者数据找不到别名字段，表示符号化之后的代码需要到默认规则中搜寻相应的中文名称
            ////如果getbyrule为false，即设置了别名字段，表示符号化之后的名称需要与别名对应，而不是到规则中去搜。一般管线数据符号化时用到该方法
            //bool getbyrule = string.IsNullOrEmpty(SystemConfig.systemConfigXml.符号化.别名字段) ||
            //    pGeoFeatLyr.FeatureClass.Fields.FindField(SystemConfig.systemConfigXml.符号化.别名字段) < 0;

            //SortedList symbolRelation = null;
            ////如果getbyrule为false，构造符号化名称与别名的对应关系，显示时用
            //if (getbyrule == false) symbolRelation = SymbolizeUtility.GetSymbolRelation(pGeoFeatLyr.FeatureClass);

            string sTitile = "";
            List<SymbolItem> m_List= SymbolHelper.GetStyles(m_StyleType,styleSet);

            foreach (string fcode in fcodes)
            {
                //if (getbyrule)
                //{
                    sTitile = GetSymbolTitleByRule(fcode);
                //}
                //else
                //{
                //    sTitile = GetSymbolTitleByAlias(fcode, symbolRelation);
                //}
                ISymbol pSymbol = null;
                foreach (SymbolItem m_SymbolItem in m_List)
                {
                    if (m_SymbolItem.Name == fcode)
                    {
                        pSymbol = m_SymbolItem.Symbol as ISymbol;
                        break;
                    }
                }
                
                if (pSymbol == null)
                {
                    pSymbol = pDefaultSymbol;
                }
                pUniqueRender.AddValue(fcode, "", pSymbol);
                pUniqueRender.set_Label(fcode, sTitile);
            }

            pUniqueRender.ColorScheme = "Custom";
            pUniqueRender.set_FieldType(0, true);

            //把符号化赋给图层
            pGeoFeatLyr.Renderer = pUniqueRender as IFeatureRenderer;
            pGeoFeatLyr.DisplayField = AppConfig.SystemConfig.符号化.符号化字段;

            // 如果是点层,需要对角度进行旋转
            if (pGeoFeatLyr.FeatureClass.ShapeType == esriGeometryType.esriGeometryPoint)
            {
                if (AppConfig.SystemConfig.符号化.角度字段 == "") return;
                if (pGeoFeatLyr.FeatureClass.Fields.FindField(AppConfig.SystemConfig.符号化.角度字段) < 0) return;
                IRotationRenderer pRotationRenderer = pGeoFeatLyr.Renderer as IRotationRenderer;
                pRotationRenderer.RotationField = AppConfig.SystemConfig.符号化.角度字段;

                //旋转方式
                esriSymbolRotationType rotationType = esriSymbolRotationType.esriRotateSymbolArithmetic;
                if (AppConfig.SystemConfig.符号化.旋转方式 == null)
                {
                    AppConfig.SystemConfig.符号化.旋转方式 = "1";
                }
                switch (AppConfig.SystemConfig.符号化.旋转方式)
                {
                    case "0":
                        rotationType = esriSymbolRotationType.esriRotateSymbolGeographic;
                        break;
                    case "1":
                        rotationType = esriSymbolRotationType.esriRotateSymbolArithmetic;
                        break;
                }
                pRotationRenderer.RotationType = rotationType;
                pGeoFeatLyr.Renderer = pRotationRenderer as IFeatureRenderer;
            }

        }

        /// <summary>
        ///通过规则得到符号名称
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string GetSymbolTitleByRule(string value)
        {
            DataImportRule dataImportRuleCur = null;
            foreach (DataImportRule dataImportRule in RuleConfig.DataBuilding.BuildingRules)
            {
                if (dataImportRule.RuleName == AppConfig.SystemConfig.符号化.默认规则)
                {
                    dataImportRuleCur = dataImportRule;
                    break;
                }
            }
            if (dataImportRuleCur == null) return value;
            foreach (DlgTargetFeatureClass featureClass in dataImportRuleCur.dlgTargetFeatureClasses)
            {
                foreach (FeatureCode code in featureClass.featureCodes)
                {
                    if (code.FCODE.Trim() == value.Trim())
                    {
                        return code.FCODE.Trim() + "  " + code.FNAME.Trim();
                    }
                }
            }
            return value;
        }

        /// <summary>
        /// 通过要素类别名获取分类代码集合
        /// </summary>
        /// <param name="aliasName"></param>
        /// <returns></returns>
        public static List<string> GetFcodesFromAliasName(string aliasName)
        {
            List<string> fcodes = new List<string>();
            DataImportRule dataImportRuleCur = null;
            foreach (DataImportRule dataImportRule in RuleConfig.DataBuilding.BuildingRules)
            {
                if (dataImportRule.RuleName == AppConfig.SystemConfig.符号化.默认规则)
                {
                    dataImportRuleCur = dataImportRule;
                    break;
                }
            }
            if (dataImportRuleCur == null) return fcodes;

            foreach (DlgTargetFeatureClass featureClass in dataImportRuleCur.dlgTargetFeatureClasses)
            {
                if (featureClass.FeatureClassAliasName == aliasName)
                {
                    foreach (FeatureCode code in featureClass.featureCodes)
                    {
                        fcodes.Add(code.FCODE.Trim());
                    }
                }
            }

            return fcodes;
        }

        /// <summary>
        /// 通过规则库中名称和代码对应关系
        /// </summary>
        /// <param name="value"></param>
        /// <param name="sortedList"></param>
        /// <returns></returns>
        public static string GetSymbolTitleByAlias(string value, SortedList sortedList)
        {
            if (sortedList == null) return value;
            if (sortedList.Contains(value.Trim()))
            {
                return value + "   " + sortedList.GetByIndex(sortedList.IndexOfKey(value));
            }
            return value;
        }
    }
}
